<template>
  <p class="mb-2">发布新商品</p>
  <!-- 分类信息 -->
  <CategoryChoice />
  <!-- 基本信息 -->
  <div class="px-4">
    <!-- 基本信息标题 -->
    <div class="text-lg font-semibold mb-4">1 基本信息</div>

    <el-form label-width="100px">
      <el-form-item label="商品轮播图">
        <div class="flex flex-col">
          <span class=" text-gray-500">图片要求：宽高比例为1:1或3:4,且宽高均大于480px,大小3M内。已上传5/10张,拖拽可调整顺序</span>

          <el-upload v-model:file-list="imagesList" action="#" :auto-upload="false" list-type="picture-card" multiple
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-change="handleMainImageChange">
            <!-- <el-icon>
              <Plus />
            </el-icon> -->
            <template #trigger>
              <div class="flex flex-col items-center space-y-2">
                <el-button style="width: 100%;">本地上传</el-button>
                <el-button style="width: 100%; margin: 0;">图片空间上传</el-button>
              </div>
            </template>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
      </el-form-item>

      <el-form-item label="商品标题">
        <el-input placeholder="请输入商品标题"></el-input>
      </el-form-item>
      <el-form-item label="商品属性">
        <div class="bg-gray-100 px-2 w-full">
          <div class="border-b border-gray-300 text-gray-400 py-2 px-4 flex justify-between">
            <span class="flex items-center">填写率<a class="text-green-500">100%</a><i
                class="text-green-500 iconfont icon-yuanhuan ml-1 font-bold "></i></span>
            <span>准确填写属性，有利于商品在搜索和推荐中露出，错误填写可能面临商品下架或流量损失</span>
            <span>没有合适属性值?点击反馈</span>
          </div>
          <!-- <div class="flex  items-center justify-between p-2 "> -->
          <div class="grid grid-cols-2 gap-4  mt-4 p-4">
            <div class="w-full" v-for="(item,index) in productAttrs">
              <div class=" flex items-center">
                <label class="w-30 ">
                  <span class="text-orange-500 pr-2" v-show="item.isImportant">重要</span>
                  {{ item.name }}
                </label>
                <!-- <el-input :placeholder="`请输入${item.name}`" v-model="form.items[index].value"
                  style="width: 70%;"></el-input> -->
                <el-select v-model="form.items[index].value" :placeholder="`请输入${item.name}`" size="large"
                  style="width: 70%" :multiple="item.isMultiple">
                  <el-option v-for="attr in item.values " :key="attr" :label="attr" :value="attr" />
                </el-select>

              </div>
              <p class="ml-31 text-gray-400" v-if="item.comment">{{item.comment}}</p>
            </div>
          </div>
          <!-- <div class="flex  items-center justify-between p-2 ">
            <div class="w-full flex items-center">
              <label class="w-12">后跟</label>
              <el-input placeholder="请输入品牌" style="width: 300px;"></el-input>
            </div>
            <div class="w-full">
              <div class=" flex items-center">
                <label class="w-30 "><span class="text-orange-500 pr-2">重要</span>鞋底材质</label>
                <el-input placeholder="请输入品牌" style="width: 300px;"></el-input>
              </div>
              <p class="ml-30 text-gray-400">该材质必须占鞋底材质30%以上</p>
            </div>
          </div> -->
        </div>
      </el-form-item>
      <el-form-item label="商品视频">
        <div class="flex flex-col">
          <span class=" text-gray-500">视频要求：时长60秒以内：宽高比为1:1或16:9或3:4.上传后展示在商品轮播图位置守卫。享全栈流量扶持，提升转化</span>
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <el-icon>
              <VideoPlay />
            </el-icon>
          </el-upload>
        </div>

      </el-form-item>
      <el-form-item label="商品详情">
        <div class="flex flex-col w-full">
          <span class=" text-gray-500">详情介绍商品以提升转化。若未编辑，商品发布后轮播图将自动填充值图文详情</span>
          <div class=" flex gap-4">
            <div class="border-1 border-gray-300 p-4 rounded-md w-1/3">
              <span class=" text-gray-500">页面预览</span>

              <!-- 商品详情图展示 -->
              <div class="space-y-4">
                <div v-for="(file, index) in detailImgList" :key="file.uid" class="relative group">
                  <img :src="file.url" :alt="'详情图' + (index + 1)" class="w-full h-auto rounded " />
                  <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                    <el-tag type="info">图{{ index + 1 }}</el-tag>
                  </div>
                </div>
              </div>
            </div>
            <div class="flex-1 border-1 border-gray-300 p-4 rounded-md">
              <div class="flex items-center text-sm text-gray-500 mb-2">
                <span class=" text-gray-500 mr-2">快捷编辑</span>
                <i class="iconfont icon-info_circle text-blue-500 mr-2"></i>
                <span>提示：支持多图上传，拖拽图片可调整顺序，最多可上传50张图片</span>
                <div class="stats-card mt-4 md:mt-0 px-4 py-3">
                  <div class="flex items-center space-x-2">
                    <i class="iconfont icon-images text-blue-500"></i>
                    <span class="font-medium">已上传:
                      <span class="text-blue-600">{{ detailImgList.length }}</span>
                      张图片</span>
                  </div>
                </div>
              </div>
              <el-upload v-model:file-list="detailImgList" action="#" list-type="picture-card" :auto-upload="false"
                :on-change="handleChange" multiple accept="image/*" class="mb-6">
                <div
                  class="upload-card w-full h-full flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-gray-300 hover:border-blue-400 cursor-pointer">
                  <el-icon class="text-3xl text-blue-500 mb-2"><i class="iconfont icon-cloud-upload-alt1"></i></el-icon>
                  <div class="text-gray-600 font-medium">点击或拖拽上传</div>
                  <div class="text-gray-500 text-sm mt-1">支持JPG/PNG格式</div>
                </div>

                <template #file="{ file }">
                  <div class="relative w-full h-full rounded-lg overflow-hidden" draggable="true"
                    @dragstart="handleDragStart($event, file)" @dragover.prevent="handleDragOver($event, file)"
                    @dragenter.prevent @drop="handleDrop($event, file)">
                    <img :src="file.url" class="w-full h-full object-cover" :alt="file.name" />

                    <!-- 图片编号 -->
                    <div class="image-number">
                      {{ detailImgList.indexOf(file) + 1 }}
                    </div>

                    <!-- 删除按钮 -->
                    <div class="delete-btn" @click="handleRemove1(file)">
                      <i class="fas fa-times"></i>
                    </div>
                  </div>
                </template>
              </el-upload>


            </div>
          </div>
        </div>
      </el-form-item>
      <div class="text-lg font-semibold mb-4">2 规格与库存</div>
      <el-form-item label="商品规格">
        <div class="bg-gray-100 w-full p-4">
          <!-- 颜色分类 -->
          <div class="mb-2">
            <label class=" mr-2">颜色分类</label>
            <span class=" text-gray-500">选择标准颜色可以增加搜索/导购机会，标准颜色还可以填写颜色备注信息(偏深、偏亮等)</span>
            <div class="flex">
              <el-input placeholder="选择或者输入主色"></el-input>
              <el-input placeholder="备注(偏深/偏浅)"></el-input>
            </div>

          </div>
          <!-- 鞋码 -->
          <div class="p-2 bg-white">
            <div class="flex items-center justify-between border-b-1 border-gray-300 p-2">
              <div class=" flex items-center  gap-4  ">
                <span class="  whitespace-nowrap">鞋码</span>
                <el-select placeholder="请选择" style="width: 200px;" size="small">
                </el-select>
                <span class=" whitespace-nowrap text-gray-500">可从尺码模版选择尺码</span>
              </div>
              <span class="text-blue-400 px-4"> 全部尺码表</span>

            </div>
            <div class="flex items-center gap-4 mt-2 p-2">
              <div class="mr-2  border border-gray-300 divide-x divide-gray-300">
                <span class="p-1">欧码</span>
                <span class="p-1">英码</span>
                <span class="p-1">美码</span>
              </div>
              <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                全选以下规格值
              </el-checkbox>
            </div>
            <!-- 鞋码展示区域 -->
            <div class="p-2">
              <el-checkbox-group v-model="checkedSize" @change="handleCheckedSizeChange">
                <div class="grid grid-cols-4 gap-2">
                  <el-checkbox v-for="size in shoeSize[0].values" :key="size" :label="size" :value="size">
                    {{ size }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>

          </div>

        </div>

      </el-form-item>
      <el-form-item label="价格及库存">
        <div class="bg-gray-100 w-full p-4">
          <span class="text-orange-400">请入如实填写库存信息，以保证商品可以在承诺发货时间内发货，避免物流违规</span>
          <el-table :data="priceAndStockData" header-row-class-name="orange-header" border
            :span-method="objectSpanMethod" class="stock-table">
            <el-table-column fixed label="颜色分类" prop="color" />
            <el-table-column label="鞋码" prop="size" />
            <el-table-column label="当前库存" prop="oldStock" />
            <el-table-column label="库存增减" width="200">
              <template #default="scope">
                <div class="flex items-center ">
                  <el-input-number v-model="scope.row.stock" @change="handleStockChange(scope.$index,scope.row)">
                    <template #decrease-icon>
                      <el-icon>
                        <Minus />
                      </el-icon>
                    </template>
                    <template #increase-icon>
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </template>
                  </el-input-number>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="改后库存">
              <template #default="scope">
                <el-input v-model="scope.row.newStock" placeholder="请输入">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="发布价(元)" prop="publishPrice" />
            <el-table-column label="现价(元)" prop="nowPrice" />
            <el-table-column label="预览图">
              <template #default="scope">
                <img :src="scope.row.image" style="width: 50px; height: 50px;" />

              </template>
            </el-table-column>
            <el-table-column label="规格编码" prop="specCode">
            </el-table-column>
            <el-table-column label="状态" fixed="right">
              <template #default="scope">
                <span v-if="scope.row.status === '1'">已上架</span>
                <span v-else>未上架</span>
                <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                  @change="handleSwitchChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item>
        <div class=" text-center w-full">
          <el-affix position="bottom" :offset="20">

            <el-button type="primary">提交</el-button>
            <el-button>保存草稿</el-button>

          </el-affix>
        </div>
      </el-form-item>
    </el-form>
  </div>


</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { Search, Plus, VideoPlay } from '@element-plus/icons-vue';
import CategoryChoice from './CategoryChoice.vue';

/***************商品主图************************* */
//商品主图
const imagesList=ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview= (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const handleMainImageChange  = (file, fileList) => {
  //获取图片
  console.log(file, fileList)
}

//商品属性
const  productAttrs = ref([
  {
    name: '品牌',
    values: ['红丽', '蓝宝', ],
  },
  {
    name: '鞋面材质',
    values: ['超纤皮', '真皮', 'PU', '人造革'],
    isImportant:true,
    comment:'该材质必须占鞋面材质30%以上'
  },
  
  {
    name: '后跟高',
    values: ['5cm-8cm', '3cm-5cm', '8cm-10cm'],
  },
  {
    name: '鞋底材质',
    values: ['发泡橡胶', 'EVA底', '牛筋底'],
    isImportant: true,
    comment: '该材质必须占鞋底材质30%以上'
  },
  {
    name: '闭合方式',
    values: ['系带', '魔术贴', '一字式扣带'],
  },
  {
    name: '风格',
    values: ['韩版', 'EVA底', '牛筋底'],
    isImportant: true,
  },
  {
    name: '上市时间',
    values: ['2025年春季', '2025年春夏季'],
  },
  {
    name: '制作工艺',
    values: ['注塑', '胶粘', '线缝','模压'],
    isImportant: true,
  },
  {
    name: '鞋面内里材质',
    values: ['网面', '超纤皮', '纯真皮'],
    comment: '该材质必须占鞋面内里材质30%以上'
  },
  {
    name: '鞋垫材质',
    values: ['超纤皮', '真皮'],
    comment: '该材质必须占鞋垫材质30%以上'
  },
  {
    name: '鞋头款式',
    values: ['圆头', '尖头', '方头','平头'],
  },
  {
    name: '跟底款式',
    values: ['松糕底', '平底', '高跟'],
    isImportant: true,
  },
  {
    name: '开口深度',
    values: ['中口', 'EVA底', '牛筋底'],
  },
  {
    name: '功能',
    values: ['防滑', '增高', '耐磨'],
    isMultiple:true
  },
  {
    name: '款式',
    values: ['包根跟', '半托'],
  },
    {
    name: '使用季节',
    values: ['不限季节', '春秋', '夏季','冬季'],
  },
  
])
const form  = reactive({
  items: productAttrs.value.map(attr => ({
    name: attr.name,
    value: '',
  })),//商品属性

})
watch(()=>form.items,(newVal,oldVal)=>{ 
  console.log(newVal,'<<<newVal',oldVal,'<<<oldVal');
},{deep:true})

/***************商品详情图************************* */
//商品详情图
const detailImgList = ref([])
const dragItem = ref(null);
// 处理文件变化
const handleChange = (uploadFile, uploadFiles) => {
  if (detailImgList.value.length >= 50) {
    ElMessage.warning("最多只能上传12张图片");
    return;
  }

  if (uploadFile.raw) {
    uploadFile.url = URL.createObjectURL(uploadFile.raw);
  }
  detailImgList.value = uploadFiles;
};

// 删除文件
const handleRemove1 = (file) => {
  const index = detailImgList.value.indexOf(file);
  if (index !== -1) {
    detailImgList.value.splice(index, 1);
    if (file.url && !file.url.includes("picsum.photos")) {
      URL.revokeObjectURL(file.url);
    }
  }
};
// 拖拽排序相关方法
const handleDragStart = (e, file) => {
  dragItem.value = file;
  e.dataTransfer.effectAllowed = "move";
  e.target.classList.add("dragging");
};

const handleDragOver = (e) => {
  e.preventDefault();
  e.dataTransfer.dropEffect = "move";
  e.target.classList.add("drag-over");
};

const handleDrop = (e, targetFile) => {
  e.preventDefault();
  e.target.classList.remove("drag-over");

  if (dragItem.value !== targetFile) {
    const oldIndex = detailImgList.value.indexOf(dragItem.value);
    const newIndex = detailImgList.value.indexOf(targetFile);

    // 交换位置
    detailImgList.value.splice(oldIndex, 1);
    detailImgList.value.splice(newIndex, 0, dragItem.value);
  }
};


// 鞋码
const  shoeSize = ref([
  {
    name: '欧码',
    values: ['35', '36', '37', '38', '39', '40', '41', '42', '35.5', '36.5', '37.5', '38.5', '39.5', '40.5', '41.5' ]
  },
  {
    name: '中国码',
    values: ['220', '225', '230', '235', '240', '245', '250', '255', '260',  ]
  },
  {
    name: '美码',
    values: ['5', '6', '7', '8', '9', '10', '11', '22', '5H', '6H', '7H', '8H', '9H', '10H', '11H' ]
  },
])
const  checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedSize = ref(['35', '36'])
const handleCheckAllChange = (val) => {
  console.log(shoeSize, 'aaaaa')
  checkedSize.value = val ? shoeSize.value[0].values : []
 
  isIndeterminate.value = false
}
const handleCheckedSizeChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === shoeSize.value[0].values.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < shoeSize.value[0].values.length
}

//价格及库存
const  priceAndStockData = ref([
  {
    color: '米白色',
    size:37,
    oldStock:200,
    newStock:200,
    nowPrice:100,
    publishPrice:100,
    image:'',
    specCode:'高丽鞋业-c-168',
    status:'1'
  },
  {
    color: '米白色',
    size:38,
    oldStock:200,
    newStock:200,
    nowPrice:100,
    publishPrice:100,
    image:'',
    specCode:'高丽鞋业-c-169',
    status:'1'
  }
])

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  // console.log(row, column, rowIndex, columnIndex);
  if (columnIndex === 0) {
    // Find all rows with the same color
    const sameColorRows = priceAndStockData.value.filter(item => item.color === row.color);
    // Find the first occurrence of this color
    const firstIndex = priceAndStockData.value.findIndex(item => item.color === row.color);
    // If this is the first row of this color group
    if (rowIndex === firstIndex) {
      return {
        rowspan: sameColorRows.length,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
}
//当库存发生变化的之后
const  handleStockChange = (index,row) => {
  console.log(index,row.stock);
  //todo 调用接口修改库存
  priceAndStockData.value[index].newStock = row.oldStock + row.stock
  
}
//开关 上架下架开关
const handleSwitchChange = (row) => {
  console.log(row);
  //todo 调用接口修改上架和下架的状态

}
</script>
<style lang="less" scoped>
.image-number {
  position: absolute;
  top: 0px;
  left: 0px;
  //   background: rgba(0, 0, 0, 0.6);
  background: rgba(43, 150, 244, 0.6);
  color: white;
  width: 28px;
  height: 28px;
  border-radius: 0 5px 5px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  z-index: 10;
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.4);
  //   border: 1px solid #f56c6c;
  //   color: #f56c6c;
  //   border: 1px solid #f0f0f0;
  color: #fff;
  width: 28px;
  height: 28px;
  border-radius: 0 10px 0 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  z-index: 10;
}

.delete-btn:hover {
  background: #f56c6c;
  color: white;
  transform: scale(1.1);
}

.upload-card {
  transition: all 0.3s ease;
  background: linear-gradient(145deg, #f0f2f5, #e4e7eb);
}

.upload-card:hover {
  background: linear-gradient(145deg, #e4e7eb, #d7dbe0);
  transform: translateY(-3px);
}

.dragging {
  opacity: 0.6;
  border: 2px dashed #409eff;
  transform: scale(0.98);
}

.drag-over {
  border: 2px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}
</style>
<style>
/* 表头样式 */
.orange-header th {
  background-color: #eee !important;
  /* 橘色背景 */
  color: #777 !important;
  /*文字颜色*/
}

/* 可选：hover效果 */
.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #ffefd5 !important;
}


</style>